package com.lottery.service.pc28.accoutService.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lottery.dao.pc28.accoutDao.LoaclauthDao;
import com.lottery.dao.pc28.accoutDao.LoginInfoDao;
import com.lottery.dao.pc28.accoutDao.UserDao;
import com.lottery.dao.pc28.lobbyDao.BettinginfoDao;
import com.lottery.dao.pc28.wealthDao.AccountDao;
import com.lottery.dao.pc28.wealthDao.AccountTransactionDao;
import com.lottery.dao.pc28.wealthDao.HistoryDao;
import com.lottery.dto.ResultDto;
import com.lottery.dto.UserInfoDto;
import com.lottery.entity.*;
import com.lottery.service.pc28.JedisClient;
import com.lottery.service.pc28.accoutService.UserService;
import com.lottery.service.pc28.customService.CostomerServer;
import com.lottery.utils.CustomerContext;
import com.lottery.utils.DateUtil;
import com.lottery.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.*;

public class UserServiceimpl implements UserService {

	@Autowired
	private UserDao userdao;

	@Autowired
	private JedisClient jedisClient;

	@Autowired
	private LoginInfoDao logindao;

	@Autowired
	private AccountTransactionDao accountTransactionDao;

	@Autowired
	private BettinginfoDao bettingInfoDao;

	@Autowired
	private AccountDao accountDao;

	@Autowired
	private HistoryDao historyDao;

	private CustomerContext customerContext;

    @Autowired
    private LoaclauthDao loaclauthdao;

	// 日志
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	// 添加用户信息
	@Override
	public int insertUser(User user) {
		// 输入信息，并获取
		user.setUserName(user.getUserName());
		user.setUserType(user.getUserType());
		user.setAgencyId(user.getAgencyId());
		user.setHeadPic(user.getHeadPic());
		user.setPhoneNum(user.getPhoneNum());
		user.setUserScore(user.getUserScore());
		user.setUserLevel(user.getUserLevel());
		user.setRealName(user.getRealName());
		user.setIdentityCard(user.getIdentityCard());
		user.setSex(user.getSex());
		user.setAge(user.getAge());
		user.setCountry(user.getCountry());
		user.setProvince(user.getProvince());
		user.setCity(user.getCity());
		user.setRemark(user.getRemark());
		user.setCreateTime(user.getCreateTime());
		user.setLastActiveTime(user.getLastActiveTime());

		// 调取这个方法
		this.userdao.insertUser(user);
		int id = user.getUserId();// 获取用户的id
		return id;
	}

	// 完善修改用户信息
	@Override
	public String updateUser(int userId, String userName, String headPic, String phoneNum, String realName,
			String identityCard, String smscode, String recommendCode, String city) {
		JSONObject jObject = new JSONObject();
		// 创建user对象
		// 判断手机号 是不是为空 ，bu为空 就判断短信验证码
		if (phoneNum != null && phoneNum.startsWith("1") && phoneNum.length() == 11) {
			try {
				Long i = Long.parseLong(phoneNum);
				logger.info("phoneNum:{}", i);
			} catch (Exception e) {
				e.printStackTrace();
				jObject.put("result", "2");
				jObject.put("msg", "手机号不正确");
				return jObject.toJSONString();
			}
		}
		// else {
		// jObject.put("result", "2");
		// jObject.put("msg", "手机号不正确");
		// return jObject.toJSONString();
		// }

		if (phoneNum != null && smscode != null) {
			String vercode1 = jedisClient.get("loginsystem" + phoneNum);
			if (!smscode.equals(vercode1)) {
				jObject.put("result", "1");
				jObject.put("msg", "短信验证码不正确");

				return jObject.toJSONString();

			}
		}
		// 判断身份证 的正则表达式^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$
		// "^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$"
		String p = "^[1-9]\\d{5}(18|19|([23]\\d))\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$";
		if (identityCard != null && !identityCard.trim().equals("") && !identityCard.matches(p)) {
			jObject.put("result", "1");
			jObject.put("msg", "身份证号不正确");
			return jObject.toJSONString();
		}

		// 昵称判断
		if (userName != null && !userName.trim().equals("") && StringUtil.strLength(userName) > 10) {
			jObject.put("result", "2");
			jObject.put("msg", "请输入1~10个英文或不超过5个中文汉字 ");
			return jObject.toJSONString();
		}

		// 昵称 不能为空
		// if (userName == null || userName.trim().isEmpty()) {
		// jObject.put("result", "1");
		// jObject.put("msg", "用户名不能为空");
		// return jObject.toJSONString();
		// }
		// 判断昵称最高不超过14个长度[a-zA-Z]{1,14}|[\u4e00-\u9fa5]{1,7},/^[\u4e00-\u9fa5a-zA-Z0-9_]+$/
		// String str = "/^[\u4e00-\u9fa5a-zA-Z0-9_]+$/";
		// if (!userName.matches(str)) {
		// jObject.put("result", "2");
		// jObject.put("msg", "请输入1~14个英文或不超过7个中文汉字 ");
		// return jObject.toJSONString();
		// }
		// 查询用户信息
		// User user = userdao.selectId(userId);

		// // 判断昵称不能 相同
		// if (user != null) {
		// if (!userName.equals(user.getUserName())) {
		// // 查询用户修改的昵称是否已经 使用
		// if (userdao.selectByName(userName) != null) {
		// jObject.put("result", "1");
		// jObject.put("msg", "昵称已经被占用");
		// return jObject.toJSONString();
		// }
		// }
		//
		// }

		// 判断用户真实姓名长度大于2
		if (realName != null && !realName.trim().equals("") && realName.length() > 5) {
			jObject.put("result", "1");
			jObject.put("msg", "输入的姓名长度不正确");
			return jObject.toJSONString();
		}
		try {
			// 插入数据 到 user
			User user = userdao.selectId(userId);
			if (user == null) {
				jObject.put("result", "5");
				jObject.put("msg", "用户不存在");
				return jObject.toJSONString();
			}
/*
			if (recommendCode != null && !recommendCode.equals("")) {
				if (user.getRecommendCode() == null || user.getRecommendCode().equals("")) {
					long st = DateUtil.dateToStamp(user.getCreateTime(), "yyyy-MM-dd HH:mm:ss");
					long cst = System.currentTimeMillis();
					if (cst - st > 15 * 24 * 3600 * 1000) {
						jObject.put("result", "4");
						jObject.put("msg", "已超过邀请码设置时间");
						return jObject.toJSONString();
					}

					User recommendCodeUser = userdao.selectByMyRecommendCode(recommendCode);
					if (recommendCodeUser == null) {
						jObject.put("result", "7");
						jObject.put("msg", "没有此邀请码");
						return jObject.toJSONString();
					}
					if (recommendCodeUser.getRecommendCode().equals(user.getMyRecommendCode())) {
						jObject.put("result", "8");
						jObject.put("msg", "不能相互推荐");
						return jObject.toJSONString();
					}

					if (recommendCode.equals(user.getMyRecommendCode())) {
						jObject.put("result", "5");
						jObject.put("msg", "邀请码不能为自己的邀请码");
						return jObject.toJSONString();
					}

				} else if (!user.getRecommendCode().equals(recommendCode)) {
					jObject.put("result", "3");
					jObject.put("msg", "邀请码不能被修改");
					return jObject.toJSONString();
				}
			} else {
				recommendCode = user.getRecommendCode();
			}
*/
			// user.setUserId(userId);
			user.setUserName(userName);
			user.setHeadPic(headPic);
			user.setPhoneNum(phoneNum);
			user.setCity(city);
			user.setRealName(realName);
			user.setIdentityCard(identityCard);
//			user.setRecommendCode(recommendCode);
			// 对表中进行更新
			userdao.updateUser(user);
			// 返回状态
			jObject.put("result", "0");
			jObject.put("msg", "修改成功");

		} catch (Exception e) {
			e.printStackTrace();
			// 返回状态
			jObject.put("result", "1");
			jObject.put("msg", "修改失败");

		}

		return jObject.toJSONString();
	}

	@Override
	public ResultDto<Map<String, Object>> getClientinformation(int serverId) {
		ResultDto<Map<String, Object>> result = new ResultDto<Map<String, Object>>();
		Map<String, Object> map = new HashMap<String, Object>();

		// 查询用户表，根据用户的id查询出用户需要的属性
		customerContext = CustomerContext.getInstance();

		CostomerServer costomerServer = customerContext.getServersMap().get(serverId);

		if (null == costomerServer) {
			result.setSuccess(true);
			result.setMessage("没有客户！");
			return result;
		}

		Map<Integer, ArrayList<CommunionMsg>> messageList = costomerServer.getMessageList();

		Set<Integer> clientIds = messageList.keySet();

		List<Integer> ids = new ArrayList<Integer>();

		for (int clientId : clientIds) {
			ids.add(clientId);
		}
		logger.info("ids={}", ids);
		if (null == ids || ids.size() == 0) {
			result.setSuccess(true);
			result.setMessage("没有需要接待的用户！");

			return result;
		}
		List<User> users = userdao.selectByUserId(ids);

		List<User> admitList = null;
		List<User> waitList = null;

		if (users.size() == 0 || null == users) {

			result.setSuccess(true);
			result.setMessage("没有需要接待的用户！");
			return result;
		}

		if (users.size() > 20) {
			// 获取20个 接待人数
			admitList = users.subList(0, 20);
			// 等待人数
			waitList = users.subList(21, users.size());
		} else {
			admitList = users;
		}

		map.put("admitList", admitList);
		map.put("waitList", waitList);
		result.setData(map);
		result.setSuccess(true);
		result.setMessage("接待成功！");
		// try {
		// } catch (Exception e) {
		//
		// result.setSuccess(false);
		// result.setMessage("接待失败！");
		// }

		return result;
	}

	/**
	 * 分享推荐功能接口
	 */
	@Override
	public String getsharedata(int userId) {
		JSONObject jObject = new JSONObject();
		try {
			// 根据用户id查询出用户信息
			User selectId = userdao.selectId(userId);

			// 查询出用户的推荐人所 获得的收益

			String selectTransactionMoney = accountTransactionDao.selectTransactionMoney(userId);
			DecimalFormat df = new DecimalFormat("#0.##");
			df.setRoundingMode(RoundingMode.FLOOR);
			selectTransactionMoney = df.format(Double.valueOf(selectTransactionMoney));
			if (selectTransactionMoney == null) {
				selectTransactionMoney = "0";
			}
			logger.info("--------------------selectTransactionMoney{}:" + selectTransactionMoney);
			// 获取出我的推荐码
			jObject.put("result", "0");
			jObject.put("myRecommendCode", selectId.getMyRecommendCode());
			jObject.put("recommendNum", userdao.SelectByrecommendCode(selectId.getMyRecommendCode()));
			jObject.put("selectTransactionMoney", selectTransactionMoney);
			logger.info("-----selectId{},selectTransactionMoney{}:" + selectId, selectTransactionMoney);

			List<History> his1 = historyDao.selectHistory("android");
			List<History> his2 = historyDao.selectHistory("ios");
			if (!his1.isEmpty()) {
				History history = his1.get(0);
				jObject.put("android", history.getUrl());
			}
			if (!his2.isEmpty()) {
				History history = his2.get(0);
				jObject.put("ios", history.getUrl());
			}

		} catch (Exception e) {
			e.printStackTrace();
			jObject.put("result", "1");
			jObject.put("msg", "分享失败 ");
		}
		logger.info("-----jObject.toJSONString{}:" + jObject.toJSONString());
		return jObject.toJSONString();
	}

	@Override
	public String getUserInfo(int userId) {

		JSONObject jObject = new JSONObject();
		try {
			// 根据用户id查询出用户信息
			User user = userdao.selectId(userId);
			if (user == null) {
				jObject.put("result", "1");
				jObject.put("msg", "用户不存在");
			} else {
				jObject.put("result", "0");
				jObject.put("userId", userId);
				jObject.put("headPic", user.getHeadPic());
				jObject.put("userName",
						(user.getRealName() == null || user.getRealName().trim().equals("")) ? user.getUserName()
								: user.getRealName());
				jObject.put("msg", "成功");
			}
		} catch (Exception e) {
			e.printStackTrace();
			jObject.put("result", "2");
			jObject.put("msg", "查询失败");
		}
		logger.info("-----jObject.toJSONString{}:" + jObject.toJSONString());
		return jObject.toJSONString();
	}

	@Override
	public String getLastLoginInfo(int userId, int pageNum, int pageSize, String startTime, String endTime) {
		// TODO Auto-generated method stub
		Map<String, Object> maxmap = new HashMap<String, Object>();
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		try {
			int skip = (pageNum - 1) * pageSize;
			Map<String, Integer> params = new HashMap<String, Integer>();
			params.put("userId", userId);
			params.put("skip", skip);
			params.put("pageSize", pageSize);
			params.put("startTime", (int) (DateUtil.dateToStamp(startTime) / 1000));
			params.put("endTime", (int) (DateUtil.dateToStamp(endTime) / 1000));
			List<LoginInfo> loginInfo = logindao.selectByIdLimit(params);
			for (LoginInfo one : loginInfo) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("time", DateUtil.timeStamp2Date(one.getLoginTime(), null));
				map.put("hostAddr", one.getHostAddr());
				list.add(map);
			}
			maxmap.put("array", list);
			maxmap.put("result", "0");
		} catch (Exception e) {
			e.printStackTrace();
			maxmap.put("result", "2");
			maxmap.put("msg", "查询失败");
		}

		return JSON.toJSONString(maxmap, true);
	}

	@Override
	public String selectUserInfoList(int userId, int pageNum, int pageSize) {
		// TODO Auto-generated method stub
		Map<String, Object> maxmap = new HashMap<String, Object>();
		List<UserInfoDto> userInfos = new ArrayList<UserInfoDto>();
		try {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("startPage", (pageNum - 1) * pageSize);
			map.put("pageSize", pageSize);
			if (userId != 0) {
				map.put("userId", userId);
				map.put("startPage", 0);
				map.put("pageSize", 1);
			}
			List<User> users = userdao.selectUserList(map);
			for (User one : users) {
				UserInfoDto oneInfo = new UserInfoDto();
				oneInfo.setPhoneNum(one.getPhoneNum());
				oneInfo.setUserId(one.getUserId());
				oneInfo.setUserName(one.getUserName());
				oneInfo.setUserState(one.getState());
				// Account account = accountDao.selectAccountByUserId(one.getUserId());
				// oneInfo.setAccountFunds(account.getAccountFunds());

				Account account = accountDao.selectAccountByUserId(one.getUserId());
				if (account != null && account.getAccountFunds() != 0) {
					DecimalFormat df = new DecimalFormat("#.00");
					double d = account.getAccountFunds();
					String format = df.format(d);
					oneInfo.setAccountFunds(format);
				} else {
					oneInfo.setAccountFunds("0.00");
				}

				Map<String, Object> params = new HashMap<String, Object>();
				params.put("userId", one.getUserId());
				int withDrawTotel = accountTransactionDao.totalWithDrawWealth(params);
				int rechargeTotel = accountTransactionDao.totalRechargeWealth(params);
				oneInfo.setRecharge(rechargeTotel);
				oneInfo.setWithDraw(withDrawTotel);
				int totalNum = bettingInfoDao.selectUserBetCount(one.getUserId());
				int winNum = bettingInfoDao.selectUserbetWinCount(one.getUserId());
				if (totalNum == 0) {
					oneInfo.setWinRate("0.0%");
				} else {
					double rate = (double) winNum / (double) totalNum * 100;
					logger.debug("***** rate: {}", rate);
					String strRate = Double.toString(rate);
					if (strRate.length() > 5) {
						strRate = strRate.substring(0, 5);
					}
					strRate = strRate + "%";
					oneInfo.setWinRate(strRate);
				}

				oneInfo.setBettingNum(totalNum);
				userInfos.add(oneInfo);
			}
			maxmap.put("array", userInfos);
			maxmap.put("result", "0");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			maxmap.put("result", "1");
			maxmap.put("msg", "查询异常");
		}

		return JSON.toJSONString(maxmap, true);
	}

	@Override
	public String updateUserState(int userId, String state) {
		Map<String, Object> maxmap = new HashMap<String, Object>();
		try {
			User user = new User();
			user.setUserId(userId);
			user.setState(state);
			userdao.updateUserState(user);
			maxmap.put("result", "0");
			maxmap.put("msg", "修改成功");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			maxmap.put("result", "1");
			maxmap.put("msg", "查询异常");
		}

		return JSON.toJSONString(maxmap, true);
	}

	@Override
	public boolean checkUsername(String username) {
        Loaclauth user = loaclauthdao.selectphone(username);
        if(user == null){
			return true;
		}else {
			return false;
		}
	}

}
